| Conditions | 3 |
| Paths | 2 |
| Total Lines | 58 |
| Code Lines | 35 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | const Response = require('../util/response') |
||
| 13 | login: async function (ctx) { |
||
| 14 | |||
| 15 | Validate(ctx, { |
||
| 16 | 'code': 'required', |
||
| 17 | }) |
||
| 18 | |||
| 19 | let appId = WechatMina.app_id |
||
| 20 | let appSecret = WechatMina.app_secret |
||
| 21 | code = ctx.input.code |
||
|
|
|||
| 22 | |||
| 23 | let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + appSecret + '&js_code=' + code + '&grant_type=authorization_code' |
||
| 24 | |||
| 25 | let result = await new Promise((resolve, reject) => { |
||
| 26 | Request(url, function (err, response, body) { |
||
| 27 | if (err) { |
||
| 28 | reject(err) |
||
| 29 | } |
||
| 30 | resolve(JSON.parse(body.toString())) |
||
| 31 | }) |
||
| 32 | }) |
||
| 33 | |||
| 34 | // result.openid = 'test' + new Date().getTime() // debug |
||
| 35 | |||
| 36 | if (!!result.openid) { |
||
| 37 | let userInfo = await ModelUser.getUserByOpenId(result.openid) |
||
| 38 | let uid |
||
| 39 | |||
| 40 | if (!!userInfo === false) { |
||
| 41 | let insertData = { |
||
| 42 | 'openid': result.openid |
||
| 43 | } |
||
| 44 | insertRes = await ModelUser.addUser(insertData) |
||
| 45 | uid = insertRes.insertId |
||
| 46 | } else uid = userInfo.id |
||
| 47 | |||
| 48 | let salt = 'OPENID:' + result.openid + ':CARD-LOGIN:' + new Date().getTime() |
||
| 49 | let token = Crypto.createHash('md5').update(salt).digest('hex').toUpperCase() |
||
| 50 | |||
| 51 | let ckey = Constant.WECHAT_SESSION + token |
||
| 52 | let cacheData = { |
||
| 53 | 'open_id': result.openid, |
||
| 54 | 'uid': uid, |
||
| 55 | } |
||
| 56 | Redis.set(ckey, JSON.stringify(cacheData)) |
||
| 57 | Redis.expire(ckey, 86400 * 30) |
||
| 58 | |||
| 59 | let data = { |
||
| 60 | 'token': token, |
||
| 61 | 'uid': uid |
||
| 62 | } |
||
| 63 | |||
| 64 | return Response.output(ctx, data) |
||
| 65 | } else { |
||
| 66 | throw new ApiError('auth.error', 'no permission') |
||
| 67 | } |
||
| 68 | |||
| 69 | |||
| 70 | }, |
||
| 71 | |||
| 73 | } |